const createError = require('http-errors')
const express = require('express')
const path = require('path')
const { verify } = require('./utils/token')

const indexRouter = require('./routes/index')
const usersRouter = require('./routes/users')
const medicineRouter = require('./routes/medicine')
const newsRouter = require('./routes/news')
const diseaseRouter = require('./routes/disease')
const hospitalRouter = require('./routes/hospital')
const officeRouter = require('./routes/office')
const expertRouter = require('./routes/expert')
const myuserRouter = require('./routes/myuser')
const presRouter = require('./routes/prescription')
const adRouter = require('./routes/ad')

const app = express()

app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'static')))
// 验证token
// app.use( verify() )

// 挂载路由器
app.use('/', indexRouter)
app.use('/users', usersRouter)
app.use('/medicine', medicineRouter)
app.use('/news', newsRouter)
app.use('/disease', diseaseRouter)
app.use('/hospital', hospitalRouter)
app.use('/office', officeRouter)
app.use('/expert', expertRouter)
app.use('/myuser', myuserRouter)
app.use('/pres', presRouter)
app.use('/ad', adRouter)

app.use(function (err, req, res, next) {
  console.log(err)
  if (err.name === 'UnauthorizedError') {
    return res.send({
      code: 401,
      message: '无效的Token'
    })
  }
  res.send({
    code: 500,
    message: '未知的错误'
  })
})

module.exports = app
